import { java } from '@codemirror/lang-java';
import CodeMirror, { Compartment } from '@uiw/react-codemirror/esm';
import { Button, Modal } from 'antd';

export interface ApiModelScriptProps {
    onValue: (val: any) => void;
}

export interface ApiModelScriptRef {
    initData: (templateData: string) => void;
}

export const ApiModelScript = memo(
    forwardRef<ApiModelScriptRef, ApiModelScriptProps>((props, ref) => {
        // JAVA编辑器
        const [visible, setVisible] = useState(false);
        const [codeVal, setCodeVal] = useState<string>('');

        // java
        const javaLang = new Compartment().of(java());

        const handleConfirm = () => {
            setVisible(false);
            props.onValue(codeVal?.toString());
        };

        const initDataSource = (templateData: string) => {
            setCodeVal(templateData);
            setVisible(true);
        };

        useImperativeHandle(ref, () => ({
            initData: (templateData: string) => {
                initDataSource(templateData);
            },
        }));

        return (
            <Modal
                title={'组装请求参数和Header的脚本'}
                open={visible}
                width={1000}
                onOk={handleConfirm}
                destroyOnClose
                maskClosable={false}
                onCancel={() => setVisible(false)}
                footer={() => (
                    <>
                        <Button onClick={() => setVisible(false)}>取消</Button>
                        <Button type="primary" onClick={handleConfirm}>确定</Button>
                    </>
                )}
            >
                <div style={{ minHeight: '42vh' }}>
                    <CodeMirror
                        value={codeVal}
                        extensions={[javaLang]}
                        onChange={(value) => {
                            setCodeVal(value);
                        }}
                        style={{ height: '400px', border: '1px solid #e8eaf0' }}
                        className="w-full min-h-20 mt-20 mb-20"
                    />
                </div>
            </Modal>
        );
    })
);
